package me.jiatao.xunfeisdk;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

/**
 * Created by JiaTao on 2018/9/18.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class ASRActivity extends UnityPlayerActivity {
    private static final String TAG = "******ASRActivity******";
    // 语音识别对象
    private SpeechRecognizer mAsr;
    private String voiceResult = "";
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int i) {
            if (i == ErrorCode.SUCCESS) {
                //Toast.makeText(ASRActivity.this, "语音识别初始化成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ASRActivity.this, "语音识别初始化失败", Toast.LENGTH_SHORT).show();
            }
        }
    };
    private RecognizerListener recognizerListener = new RecognizerListener() {
        @Override
        public void onVolumeChanged(int i, byte[] bytes) {

        }

        @Override
        public void onBeginOfSpeech() {
            UnityPlayer.UnitySendMessage("RecognizerObject", "onBeginOfSpeech", "onBeginOfSpeech");
        }

        @Override
        public void onEndOfSpeech() {
            UnityPlayer.UnitySendMessage("RecognizerObject", "onEndOfSpeech", "onEndOfSpeech");
        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) {
            voiceResult = JsonParser.parseGrammarResult(recognizerResult.getResultString());
            Log.i("11111111", voiceResult);

            UnityPlayer.UnitySendMessage("RecognizerObject", "onRecognizerResult", voiceResult);
        }

        @Override
        public void onError(SpeechError speechError) {
            UnityPlayer.UnitySendMessage("RecognizerObject", "onRecognizerError", speechError.getErrorDescription());
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    // 语音合成对象
    private SpeechSynthesizer mTts;
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            if (code == ErrorCode.SUCCESS) {
                //Toast.makeText(ASRActivity.this, "语音合成初始化成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ASRActivity.this, "语音合成初始化失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private SynthesizerListener mTtsListener=new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {
            UnityPlayer.UnitySendMessage("RecognizerObject", "onSpeakBegin", "onBeginOfSpeech");
        }

        @Override
        public void onBufferProgress(int i, int i1, int i2, String s) {

        }

        @Override
        public void onSpeakPaused() {

        }

        @Override
        public void onSpeakResumed() {

        }

        @Override
        public void onSpeakProgress(int i, int i1, int i2) {

        }

        @Override
        public void onCompleted(SpeechError speechError) {
            UnityPlayer.UnitySendMessage("RecognizerObject", "onSpeakCompleted", "onBeginOfSpeech");
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化识别对象
        SpeechUtility.createUtility(this, "appid=5ba05df4");
        mAsr = SpeechRecognizer.createRecognizer(this, mInitListener);

        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
    }


    public void startRecognizer() {
        voiceResult = "";
        mAsr.setParameter(SpeechConstant.DOMAIN, "iat");
        mAsr.setParameter(SpeechConstant.ACCENT, "mandarin");
        mAsr.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mAsr.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "4000");
        mAsr.setParameter(SpeechConstant.VAD_EOS, "2000");
        mAsr.setParameter(SpeechConstant.ASR_PTT, "0");
        mAsr.startListening(recognizerListener);


//1.创建 RecognizerDialog 对象
//        RecognizerDialog mDialog = new RecognizerDialog(this, mInitListener);

//若要将 RecognizerDialog 用于语义理解，必须添加以下参数设置，设置之后 onResult 回调返回将是语义理解的结果
//        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
//        mDialog.setParameter("asr_sch", "1");
//        mDialog.setParameter("nlp_version", "3.0");

//3.设置回调接口
//        mDialog.setListener(mRecognizerDialogListener);

//4.显示 dialog，接收语音输入
//        mDialog.show();
    }

    public void startSpeak(String text,String voicer) {
        setSpeakParam(voicer);
        int code =  mTts.startSpeaking(text, mTtsListener);
        if (code != ErrorCode.SUCCESS) {
            Toast.makeText(this, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show();
        }
    }

    private void setSpeakParam(String voicer) {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        //onevent回调接口实时返回音频流数据
        //mTts.setParameter(SpeechConstant.TTS_DATA_NOTIFY, "1");
        // 设置在线合成发音人
        mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
        //设置合成语速
        mTts.setParameter(SpeechConstant.SPEED, "45");
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, "50");
        //设置合成音量
        mTts.setParameter(SpeechConstant.VOLUME,"60");
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "pcm");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.pcm");
    }
}
